package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import uit.edu.vn.Model.myFile;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.FileListAdapter;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.httpUploader;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class FileActivity extends MyActivity{

	 private List<myFile> listFile = null;
	 private List<String> path = null;
	 private Handler handler;
	 private ProgressDialog loadingFileDialog;
	 private int numberOfItemSelected = 0;
	 private Resources res;
	 private TextView myPath;
	 private ListView listview;
	 private FileListAdapter fAdapter;
	 private String root="/sdcard";
	 private ArrayList<myFile> itemFileCheck= new ArrayList<myFile>(); 
	// private String urlString = "http://10.0.2.2:8080/ServerWeb/UploadServlet.jsp";
	 private Context context;
     private String urlString = "";
     private String userid = "";
     private String username = "";
     private String password = "";
     private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
     private SharedPreferences ShareRef = null;
	 private int filetype = 3;
	 private String Size;
	 private AESControl aes;
	 private Thread myFileThread;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
        urlString = "http://"+ getSetting("address")+"/ServerWeb/UploadServlet.jsp"; 
		
		setContentView(R.layout.backup_file);
        //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
      if(username.equals("") && password.equals("")){
          Intent intent = new Intent(FileActivity.this, LoginActivity.class);
          startActivity(intent);
          this.finish();            	
      }		
      
      System.out.println("FileActivity");
      System.out.println("username: "+ username);
      System.out.println("password: "+ password);
      System.out.println("userid:   "+ userid);
      System.out.println("address:   "+ urlString);
//		
		res=getResources();
	    listview=(ListView)findViewById(R.id.listFileBackup);
	    myPath= (TextView)findViewById(R.id.txt_titleFile);
	    context=getBaseContext();
	    Log.d("urlString in FileActivity: ",urlString);
	    loadingFileDialog= new ProgressDialog(this);
	    loadingFileDialog.setMessage(getResources().getString(R.string.dialog_message_progress));
	    loadingFileDialog.setCancelable(false);
	    loadingFileDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    loadingFileDialog.show();
	  
		// tao thread backgroundthread tach roi voi UI
		handler= new Handler();
		myFileThread= new Thread(null,BackGroundThread,"File Background");
		myFileThread.start(); 
		
		getDir(root);
	}
	
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	} 	
	//ham xu ly thread
	public Runnable BackGroundThread = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			doinBackGround();
		}
	};
	private void doinBackGround()
	{

		 handler.post(doUpdateUI);
	}
	public Runnable doUpdateUI = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			//updateGUI();
			loadingFileDialog.dismiss();
		
		}
	};
	
	private void getDir(String dirPath)
    {
		 
    	// gán dường dẫn vào text view 
		myPath.setText(getResources().getString(R.string.title_BackupHeaderFile)+dirPath);
    	listFile = new ArrayList<myFile>();
    	//path để lưu đường dẫn
    	path = new ArrayList<String>();
    	File f = new File(dirPath);
    	//liệt kê danh sách các file 
    	File[] files = f.listFiles();
    	// sap xep theo anpha ,beta
    	Arrays.sort(files);
    	if(!dirPath.equals(root))
    	{
    		listFile.add(new myFile("../","","", res.getDrawable(R.drawable.ic_back)));
    		path.add(f.getParent());          
    	}
    	for(int i=0; i < files.length; i++)
    	{
    		File file = files[i];
    		path.add(file.getPath()); 	
    		if(file.isDirectory())
    		{
    			
    			listFile.add(new myFile(file.getName(),file.getPath(),"" , res.getDrawable(R.drawable.ic_file_selector)));
    		}
    		else 
    		{
    			String nameFile=file.getName().toLowerCase();
    			Size=String.valueOf(file.length());
    			//Size=getFileSize(Size);
    			if(nameFile.endsWith("mp3"))
    			{
    				listFile.add(new myFile(file.getName(),file.getPath(),Size, res.getDrawable(R.drawable.ic_music_selector)));
    		    	
    			}
    			else if(nameFile.endsWith("png")||nameFile.endsWith("jpg")||nameFile.endsWith("jpeg")||nameFile.endsWith("jpg"))
    			{
    				listFile.add(new myFile(file.getName(),file.getPath(),Size, res.getDrawable(R.drawable.ic_image_selector)));
    		    	
    			}
    			else
    			{
    				listFile.add(new myFile(file.getName(), file.getPath(),String.valueOf(file.length()),res.getDrawable(R.drawable.ic_text)));
    			}
    		}
    	}  	
    	listview.setOnItemClickListener(new OnItemClickListener() 
    	{
		 @Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
    				long arg3) {
    			// TODO Auto-generated method stub
    			 final File file =new File(path.get(position));
    	    	if(file.isDirectory())
    	    	{
    	    		if(file.canRead())
    	    		{
    	    			getDir(path.get(position));
    	    	    	
    	    		}
    	    		else
    	    		{
    	    			showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_khongmo), new OnClickListener() 
    	    			{
							
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								// TODO Auto-generated method stub
								dialog.cancel();
							}
						});
    	    		}
    	    	}
    	    	else 
    	    	{
    	    		// TODO Auto-generated method stub
					//hien dialog bao mo file vag goi intent de mo file 
    	    		try {
    	    			showConfirmDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_mo), new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) 
							{
								// TODO Auto-generated method stub
								try {
									// dua vao duoi file de goi intent tuong ung .
									File temp= new File(file.getAbsolutePath());
									String nameTemp=temp.getName().toLowerCase();
									Intent myIntent = new Intent();
									myIntent.setAction(android.content.Intent.ACTION_VIEW);
									if(nameTemp.endsWith("mp3"))
									{
										myIntent.setDataAndType(Uri.fromFile(temp), "audio/*") ;                               	
									}	
									else if(nameTemp.endsWith("png")||nameTemp.endsWith("gif")||nameTemp.endsWith("jpeg")||nameTemp.endsWith("jpg"))
									{
										myIntent.setDataAndType(Uri.fromFile(temp), "image/*") ;
									}
									else if(nameTemp.endsWith("txt")||nameTemp.endsWith("xml"))
									{
										myIntent.setDataAndType(Uri.fromFile(temp), "text/*") ;		
									}
									else
									{
										showToast("Khong The Mo File Nay");
									}
			                     	startActivity(myIntent);
								
								} catch (Exception e) 
								{
									// TODO: handle exception
									e.printStackTrace();
								}
							}
							
						});
					} catch (Exception e) {
						// TODO: handle exception
						  e.printStackTrace();
					}

    	    		
    	    	}
    		}
		});
    	fAdapter = new FileListAdapter( getBaseContext(),listFile);
    	listview.setAdapter(fAdapter);
	    
    }
	//--------------------------xu ly menu---------------------------------
    public boolean onCreateOptionsMenu(Menu menu) {
    	// TODO Auto-generated method stub
    	
    	new MenuInflater(getApplicationContext()).inflate(R.menu.backup_file_option_menu, menu);
	    return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
    	// TODO Auto-generated method stub
    	 if(numberOfItemSelected==listFile.size())
  	   {
  		   menu.findItem(R.id.menu_fileSelectAll).setTitle(getResources().getString(R.string.txt_uncheckall));
  	   }
  	   else
  	   {
  		   menu.findItem(R.id.menu_fileSelectAll).setTitle(getResources().getString(R.string.txt_checkall));
  		      
  	   }
    	return super.onMenuOpened(featureId, menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// TODO Auto-generated method stub
    	switch(item.getItemId())
    	{
    		case R.id.menu_fileBackup:
    			// xu ly chon file check
				//neu flag =1 thì đã có sms check roi 
				//flag=0 nghia là chưa có chon sms nao
				int flag=0;
				for(int i=0;i<listFile.size();i++)
				{
					if(listFile.get(i).getChecked()==true)
					{
						flag=1;
						numberOfItemSelected++;
					}
				
				}
				if(flag==0)
				{
					numberOfItemSelected=0;
				}
    			//xu ly backup
				if(listFile.isEmpty())
				{
					showToast("list trống");
				}
				else
				{
					if (numberOfItemSelected==0) 
					{
						showToast("Vui long chọn tập tin cần sao lưu");
					}
					else
					{
						showConfirmDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_server), new OnClickListener() 
						{
							
							@Override
							public void onClick(DialogInterface dialog, int which) 
							{
								// TODO Auto-generated method stub
								//check ket noi internet 
								CheckInternet chkI= new CheckInternet(context);
						        if(chkI.checkStatus().equals(true))
								{

						        	new BackupServerTask().execute();
						        	
								}
						        else
						        {
						        	Log.d("ketnoi", "ko co ket noi internet");
						        	showToast("Khong co ket noi internet");
						        
						        }
								
								
								
							}
						});
					}
				}

    				
    			
    			return true;
    			
    		case R.id.menu_fileLogout:
    			logOut();
                Intent intent = new Intent(FileActivity.this, LoginActivity.class);
                startActivity(intent);
                this.finish();
    			return true;
    		case R.id.menu_fileDelete:
	    		int flag1=0;
				for(int i=0;i<listFile.size();i++)
				{
					if(listFile.get(i).getChecked()==true)
					{
					flag1=1;
					numberOfItemSelected++;

					}	
				}
				if(flag1==0)
				{
					numberOfItemSelected=0;
				}
				if(numberOfItemSelected==0)
				{
					showToast("Vui lòng chọn tập tin cần xoá");
				}
				else{
	    		showConfirmDialog(getResources().getString(R.string.dialog_canhbao), getResources().getString(R.string.dialog_message_xoa), new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						for(int i=0;i<listFile.size();i++)
						{
							myFile entry=listFile.get(i);
							if(entry.getChecked()==true)
							{
								Log.d("i",String.valueOf(i));
								
								File temp = new File(entry.getPath());
								Boolean delete= temp.delete();
								Log.d("i",entry.getPath());
								listFile.remove(i);
								fAdapter.notifyDataSetChanged();
	    						if(delete ==true)
								{
	    							
									i--;
									Log.d("i",String.valueOf(i));
								}	
	    						numberOfItemSelected--;
	    					
							}
						}	
	    		
	    			showAlertDialog("Thông Báo !", "Xóa Thành Công ", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
							dialog.cancel();
						}
					});
					}
	    		}).show();
				}
	    			return true;
    		case R.id.menu_fileSelectAll:
    			//xu ly check all
    			if(numberOfItemSelected==listFile.size())
    			{
    				// xu ly bo chon
    				for(int i=0;i<listFile.size();i++)
    				{
    					listFile.get(i).setChecked(false);
    				
    				}
    				numberOfItemSelected=0;
    			}
    			else
    			{
    				// xu ly chon
    				for(int i=0;i<listFile.size();i++)
    				{	
    					listFile.get(i).setChecked(true);
    				}
    				numberOfItemSelected=listFile.size();
    			}
    				fAdapter.notifyDataSetChanged();
    			return true;
    	}
    	return false;
    }   
    public class BackupServerTask extends AsyncTask<Void, Void, Void>
    {
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    		  loadingFileDialog.setMessage(getResources().getString(R.string.dialog_message_progress_up_server));
			loadingFileDialog.show();
    	}
    	@Override
    	protected Void doInBackground(Void... params) {
    		// TODO Auto-generated method stub
    	
			try {
				for(int i=0;i<listFile.size();i++)
				{
					if(listFile.get(i).getChecked()==true)
					{
						myFile entry =listFile.get(i);
						itemFileCheck.add(entry);
					}
				}
				backupFileToServer(itemFileCheck);


			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return null;
    	}
    	@Override
    	protected void onPostExecute(Void result) {
    	
    		// TODO Auto-generated method stub
			loadingFileDialog.dismiss();	
//			duyet mang và set check lai false
			for(int i=0;i<listFile.size();i++)
			{
				listFile.get(i).setChecked(false);
			}
			fAdapter.notifyDataSetChanged();
			showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_saoluuthanhcong), new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});
			super.onPostExecute(result);
    	}
    }
    public void backupFileToServer(ArrayList<myFile> fileBackup)
    {
        try {
            System.out.println("urlString in FileActivity2: "+urlString);
            System.out.println("userid in FileActivity2: "+userid);
        		//thuc hien ghi du lieu len file
        	String fileName = "";
        	for(int i= 0; i<fileBackup.size(); i++)
        	{
        		File file = new File(fileBackup.get(i).getPath());
        	//	FileInputStream fis =  new FileInputStream(file);
        		fileName = file.getName();
        		Log.d("filename", file.getName()+file.getPath());
        		// xử lý mã hóa tập tin 
        		String output = fileBackup.get(i).getPath()+".aes";
        		Log.d("output", output);
        		aes = new AESControl(username);
        		aes.EncFile(fileBackup.get(i).getPath(), output);
        		FileInputStream fis1= new FileInputStream(output);
        		
        		String temp = String.valueOf(userid)+"@"+String.valueOf(filetype)+"@"+"sao luu tap tin len may chu!";
        		Log.d("temp", temp);
                httpUploader htfu = new httpUploader(urlString,temp, fileName);
                System.out.println("chuoi tra ve la: "+htfu.doStart(fis1));
                //xóa file đã mã hóa 
                File encryptFile= new File(output);
                encryptFile.delete();
        	} 
            //lay cac thong tin cua file gui len server de ghi len database
            //bat dau upload file len server
            //hoan tat upload file va ghi thong tin file len server
            //xoa file tam da tao tren sdcard
        	
        		
        } catch (IOException e) {
          System.out.println("loi khi sao luu len Server !");
        }                
    }
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
    	if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
//    		finish();
    	}
    	return super.onKeyDown(keyCode, event);
    }

}
